package aszm.chahaospider.parser.shouji;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import aszm.chahaospider.constants.Constants;
import aszm.chahaospider.utils.MybatisUtils;
import aszm.chahaospider.utils.Utils;
import chaohao.mybatis.dao.ISPDtoMapper;
import chaohao.mybatis.model.ISPDto;

public class ShoujiParser {
	private static final Logger Log = Logger.getLogger(ShoujiParser.class.getName());

	public static void getShoujiFromWeb(String url, boolean writeDb) {
		Document doc = Utils.getDocumentDoc(url);
		Elements links = doc.select("div.noi p");
		if (writeDb) {
			Log.info(links.size() + "开始写入 Shoujis ……");
			createFile(links);
		} else {
			parserShouji(links);
		}
	}

	public static List<ISPDto> getShoujiFromDB(String number) {
		SqlSession s = MybatisUtils.getSqlSession();
		List<ISPDto> isps = s.getMapper(ISPDtoMapper.class).selectByNumber(number);
		s.close();
		return isps;
	}

	public static List<ISPDto> getAllShoujiFromDB() {
		SqlSession s = MybatisUtils.getSqlSession();
		List<ISPDto> isps = s.getMapper(ISPDtoMapper.class).selectAll();
		s.close();
		return isps;
	}

	private static void createFile(Elements links) {
		SqlSession session = MybatisUtils.getSqlSession();
		for (Element element : links) {
			String name = element.ownText().replace("手机号段：", "");
			Elements numbers = element.select("a");
			for (Element element1 : numbers) {
				ISPDto isp = parser(element1, name);
				session.getMapper(ISPDtoMapper.class).insert(isp);
			}
			session.commit();
			MybatisUtils.closeSession(session);
			Log.debug(name + "手机号段数量" + numbers.size());
		}
	}

	private static List<ISPDto> parserShouji(Elements links) {
		List<ISPDto> isps = new ArrayList<ISPDto>();
		for (Element element : links) {
			String name = element.ownText().replace("手机号段：", "");
			Elements numbers = element.select("a");
			for (Element element1 : numbers) {
				ISPDto isp = parser(element1, name);
				isps.add(isp);
			}
			Log.debug(name + "手机号段数量" + numbers.size());
		}
		return isps;
	}

	private static ISPDto parser(Element element1, String name) {
		ISPDto isp = new ISPDto();
		String url = element1.attr("href").replaceFirst("./", Constants.SHOUJI_URL);
		String number = element1.text();
		isp.setName(name);
		isp.setNumber(number);
		isp.setUrl(url);
		Log.debug(name + "-" + number + "-" + url);
		return isp;
	}
}
